import json
import os
from datetime import datetime

from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError
from django.http import JsonResponse
from django.views import View
# 直接使用PyJWT生成令牌
import jwt
import datetime
from django.conf import settings as django_settings

from user.models import User, UserSerializer


# Create your views here.


class LoginView(View):
    def post(self, request):
        try:
            # 解析请求数据，处理request.body可能是字符串或字节的情况
            try:
                if isinstance(request.body, str):
                    data = json.loads(request.body)
                else:
                    data = json.loads(request.body.decode("utf-8"))
            except json.JSONDecodeError:
                return JsonResponse({'code': 400, 'message': '无效的JSON格式'})

            username = data.get('username')
            password = data.get('password')

            # 检查参数是否存在
            if not username or not password:
                return JsonResponse({'code': 400, 'message': '用户名和密码不能为空'})

            try:
                user = User.objects.get(username=username, password=password)

                payload = {
                    'user_id': user.id,
                    'username': user.username,
                    'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
                }

                token = jwt.encode(
                    payload,
                    django_settings.JWT_AUTH['JWT_SECRET_KEY'],
                    algorithm=django_settings.JWT_AUTH['JWT_ALGORITHM']
                )

                # PyJWT>=2.0.0返回字符串而不是字节
                if isinstance(token, bytes):
                    token = token.decode('utf-8')

                return JsonResponse({
                    'code': 200,
                    'token': token,
                    'user': UserSerializer(user).data,
                    'message': '登录成功'
                })
            except User.DoesNotExist:
                return JsonResponse({'code': 400, 'message': '用户名或密码错误'})
        except Exception as e:
            print(f"登录失败异常: {str(e)}")  # 打印异常信息以便调试
            return JsonResponse({'code': 500, 'message': f'登录失败，系统错误: {str(e)}'})


class RegisterView(View):
    def post(self, request):
        try:
            # 解析请求数据，处理request.body可能是字符串或字节的情况
            try:
                if isinstance(request.body, str):
                    data = json.loads(request.body)
                else:
                    data = json.loads(request.body.decode("utf-8"))
            except json.JSONDecodeError:
                return JsonResponse({'code': 400, 'message': '无效的JSON格式'})

            username = data.get('username')
            password = data.get('password')
            confirmPassword = data.get('confirmPassword')

            # 检查两次输入的密码是否一致
            if password != confirmPassword:
                return JsonResponse({'code': 400, 'message': '两次输入的密码不一致'}, status=400)

            # 检查用户名是否已存在
            if User.objects.filter(username=username).exists():
                return JsonResponse({'code': 400, 'message': '用户已存在'}, status=400)

            # 创建新用户
            user = User(username=username, password=password, avatarUrl='/media/userAvatar/default.png')
            user.save()

            return JsonResponse({'code': 200, 'message': '用户注册成功'}, status=201)
        except IntegrityError as e:
            # 捕获数据库完整性错误
            return JsonResponse({'code': 500, 'message': '数据库错误'}, status=500)
        except Exception as e:
            # 捕获其他异常
            print(f"注册失败异常: {str(e)}")
            return JsonResponse({'code': 500, 'message': str(e)}, status=500)


class GetLoginUserView(View):
    def post(self, request):
        try:
            # 解析请求数据，处理request.body可能是字符串或字节的情况
            try:
                if isinstance(request.body, str):
                    data = json.loads(request.body)
                else:
                    data = json.loads(request.body.decode("utf-8"))
            except json.JSONDecodeError:
                return JsonResponse({'code': 400, 'message': '无效的JSON格式'})

            userId = data.get('id')
            user = User.objects.get(id=userId)
            # 更新用户登录时间（login_date会自动更新，因为设置了auto_now=True）
            user.save()
            return JsonResponse({'code': 200, 'data': UserSerializer(user).data, 'message': '用户信息'})
        except Exception as e:
            print(f"获取用户信息失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': '获取用户信息失败'})


class ImageView(View):
    def post(self, request):
        file = request.FILES.get('avatar')
        print('file', file)
        if file:
            # 确保目录存在
            avatar_dir = os.path.join(django_settings.MEDIA_ROOT, "userAvatar")
            os.makedirs(avatar_dir, exist_ok=True)

            file_name = file.name
            suffixName = file_name[file_name.rfind("."):]
            new_file_name = datetime.now().strftime('%Y%m%d%H%M%S') + suffixName

            # 使用os.path.join确保路径分隔符正确
            file_path = os.path.join(avatar_dir, new_file_name)
            print('file_path', file_path)

            try:
                with open(file_path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)

                # 返回相对路径，前端可以拼接基础URL
                relative_path = '/media/userAvatar/' + new_file_name
                return JsonResponse({
                    'code': 200,
                    'data': relative_path,
                    'message': '上传成功'
                })
            except Exception as e:
                print(f"头像上传失败: {str(e)}")
                return JsonResponse({'code': 500, 'message': f'上传头像失败: {str(e)}'})
        else:
            return JsonResponse({'code': 400, 'message': '未接收到头像文件'})


class UpdateAvatarView(View):
    def post(self, request):
        try:
            # 解析请求体中的 JSON 数据
            try:
                if isinstance(request.body, str):
                    data = json.loads(request.body)
                else:
                    data = json.loads(request.body.decode("utf-8"))
            except json.JSONDecodeError:
                return JsonResponse({'code': 400, 'message': '无效的JSON格式'})

            id = data.get('id')
            avatar = data.get('avatar')

            # 验证必要的字段是否存在
            if not id or not avatar:
                return JsonResponse({'code': 400, 'message': 'avatar字段不存在'})
            # 获取用户对象
            obj_user = User.objects.get(id=id)
            # 更新头像 URL
            obj_user.avatarUrl = avatar
            obj_user.save()
            return JsonResponse({'code': 200, 'message': '头像更新成功'})

        except ObjectDoesNotExist:
            return JsonResponse({'code': 404, 'message': '用户不存在'})
        except Exception as e:
            print(f"更新头像失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': str(e)})


class UpdateUserInfoView(View):
    def post(self, request):
        try:
            # 解析请求体中的 JSON 数据
            try:
                if isinstance(request.body, str):
                    data = json.loads(request.body)
                else:
                    data = json.loads(request.body.decode("utf-8"))
            except json.JSONDecodeError:
                return JsonResponse({'code': 400, 'message': '无效的JSON格式'})

            id = data.get('id')
            avatar = data.get('avatar')

            # 验证必要的字段是否存在
            if not id or not avatar:
                return JsonResponse({'code': 400, 'message': 'avatar字段不存在'})
            # 获取用户对象
            obj_user = User.objects.get(id=id)
            # 更新头像 URL
            obj_user.avatarUrl = avatar
            obj_user.save()
            return JsonResponse({'code': 200, 'message': '用户信息更新成功'})

        except ObjectDoesNotExist:
            return JsonResponse({'code': 404, 'message': '用户不存在'})
        except Exception as e:
            print(f"更新用户信息失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': str(e)})



